#! /usr/bin/env python3
# -*-coding: utf-8-*-

"""
Created on Apr 5 2017

@author: Moonkie

@attention: 
"""


import os
import sys
from multiprocessing import cpu_count
import mxnet as mx
from . import mtcnn
# import mtcnn


CURDIR = os.path.dirname(__file__)
ROOT = os.path.split(os.path.dirname(__file__))[0]
# ROOT = "C:\\Users\\moonkie\\codes\\imgso"  ##### test
DATASETS = os.path.join(ROOT,'datasets')
FACES = os.path.join(DATASETS,'faces')
FACEFEATURESDIR = os.path.join(DATASETS,'features')
EXEC_PREFIX = os.path.join(sys.exec_prefix,'python.exe')


def detect_face(imgpath,num_pool=int(cpu_count()/2),ctx='cpu',accurate_landmark=False):
    if not os.path.exists(DATASETS):
        raise Exception("Must initial before run.")
    
    if sys.platform == 'win32':
        execfile = os.path.join(CURDIR,'mtcnn.py')
        if not os.path.exists(EXEC_PREFIX):
            raise Exception("Python executor \"python.exe\" not found in %s,if you rename the executor,please rewrite the code in cnn/__init__.py line 27 ")
        order = '%s %s -i %s -f %s -F %s -n %s -k %s -c %s' % (EXEC_PREFIX,execfile,imgpath,FACES,FACEFEATURESDIR,num_pool,str(accurate_landmark),ctx)
        out = os.popen(order)
        rsl = out.read()
        print(rsl)
        return rsl
    elif sys.platform == 'linux2' or sys.platform == 'darwin':
        rsl = mtcnn.main(imgpath=imgpath,facesdir=THUMBNAILS,facefeaturesdir=FACEFEATURESDIR,
                    num_pool=num_pool,ctx=ctx,accurate_landmark=accurate_landmark)
        return rsl
    else:
        raise Exception('[QAQ] Not support system platform. Dont ask me why!')


def getChipFeatureData(filepath,point=None):
    '''Upack given face chips feature data 

    Parameters:
    ----------
        filepath: path of chips compress package

    return:
    -------
        A tuple "(mix,src_path)"
        mix: a zip iterator contain chip_names,chip_points,face_boxes,face_points
        src_path: source image path
    '''
    import numpy as np
    data = np.load(filepath)
    # chip_names = data['chip_names']
    # chip_boxes = data['chip_boxes']
    # chip_points = data['chip_points']
    # face_boxes = data['face_boxes']
    # face_points = data['face_points']
    if point:
        return data[point]
    src_path = data['imgpath']
    mix = zip(data['chip_names'],data['chip_boxes'],data['chip_points'],data['face_boxes'],data['face_points'])
    return mix,src_path

if __name__ == '__main__':
    # print(os.path.split(os.path.dirname(__file__))[0])
    # child = sp.Popen(['cmd'],shell=True,stdout=sp.PIPE,stdin=sp.PIPE,stderr=sp.PIPE)
    # stdout,stderr = child.communicate(input=b'mx\n python %s %i %s %')
    # child.communicate(input=b'python mtcnn.py')
    # print(stdout)
    detect_face('test.jpg',ctx='gpu')








